package system

import (
	"context"

	"admin_template/bff/admin/hertz_gen/base"
	genSysSso "admin_template/bff/admin/hertz_gen/system/sys_sso"
	"admin_template/bff/admin/internal/pkg/utils"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
)

type SSOService struct {
	*Service
}

func NewSSOService(s *Service) *SSOService {
	return &SSOService{s}
}

// Login .
// @router /v1/system/sso [POST]
func (s *SSOService) Login(ctx context.Context, c *app.RequestContext) {
	var req genSysSso.LoginRequest
	ok := s.BindAndValidate(ctx, c, &req)
	if !ok {
		return
	}
	isOk := s.captchaRepo.Verify(req.CaptchaId, req.Captcha)
	if isOk == false {
		reply := &base.BaseReply{
			Code: base.ErrCode_Fail,
			Msg:  "验证码错误",
		}
		utils.Reply(c, consts.StatusOK, &reply)
		return
	}
	userInfo, err := s.userRepo.Auth(ctx, req.Username, req.Password)
	if err != nil {
		utils.ReplyWithErr(c,
			ctx,
			"sysUserRepo Auth",
			"用户名或密码错误",
			s.CtxLogger, err)
		return
	}
	jwt := utils.NewJWT(s.Config.SystemConfig.Jwt.SigningKey,
		s.Config.SystemConfig.Jwt.Issuer, int64(s.Config.SystemConfig.Jwt.BufferTime),
		int64(s.Config.SystemConfig.Jwt.ExpiresTime))
	claims := jwt.CreateClaims(utils.BaseClaims{
		UUID:      userInfo.UserUuid,
		AK:        s.Config.SystemConfig.Jwt.SigningKey,
		RoleID:    userInfo.RoleId,
		CompanyID: userInfo.CompanyId,
	})
	token, err := jwt.CreateToken(claims)
	if err != nil {
		utils.ReplyWithErr(c,
			ctx,
			"jwt CreateToken",
			"",
			s.CtxLogger, err)
		return
	}
	reply := &genSysSso.LoginReply{
		Code: base.ErrCode_Success,
		Msg:  "成功成功",
		Data: &genSysSso.LoginData{
			UserInfo:  userInfo,
			Token:     token,
			ExpiresAt: claims.ExpiresAt.Unix(),
		},
	}
	utils.Reply(c, consts.StatusOK, &reply)

}

// Logout .
// @router /v1/system/sso [DELETE]
func (s *SSOService) Logout(ctx context.Context, c *app.RequestContext) {
	reply := base.BaseReply{
		Code: base.ErrCode_Success,
		Msg:  "登出成功",
	}
	utils.Reply(c, consts.StatusOK, &reply)
}
